package com.aispeech.jarpc.op.post;

import com.aispeech.jarpc.TextBin;
import com.aispeech.jarpc.op.AbstractRequest;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class OfflineRequest extends AbstractRequest {
    private final static String REQ_TMPL = "{\"op\":\"post\",\"sample_rate\":%d,\"lang\":\"%s\",\"use_aux\":%d,\"feed\":{\"env\":\"%s\",\"pcm_path\":\"%s\",\"aligns\":%s}}";

    private int sampleRate;
    private String lang;
    private String env;
    private String pcmPath;
    private int useAux = 0;
    private List<Align> aligns;

    public OfflineRequest(int sampleRate, String lang, String env) {
        this(sampleRate, lang, 0, env, "");
    }

    public OfflineRequest(int sampleRate, String lang, int useAux, String env, String pcmPath) {
        this.sampleRate = sampleRate;
        this.lang = lang;
        this.useAux = useAux;
        this.env = env;
        this.pcmPath = pcmPath;

        aligns = new ArrayList<>();
    }

    public void add(int begin, int end, String rec) {
        aligns.add(new Align(begin, end, rec));
    }

    public void add(int begin, int end, char speaker, String rec) {
        aligns.add(new Align(begin, end, String.valueOf(speaker), rec));
    }

    public int size() {
        return aligns.size();
    }

    @Override
    public String OpType() {
        return "post";
    }

    @Override
    public String toJson() throws IOException {
        return String.format(REQ_TMPL, sampleRate, lang, useAux, env, pcmPath, new ObjectMapper().writeValueAsString(aligns));
    }

    public TextBin toJsonBin() throws IOException {
        String json = toJson();
        return new TextBin(json, new byte[0]);
    }

    public class Align {
        private int begin;
        private int end;
        private String speaker;
        private String rec;

        public Align(int begin, int end, String rec) {
            this(begin, end, "", rec);
        }

        public Align(int begin, int end, String speaker, String rec) {
            this.begin = begin;
            this.end = end;
            this.speaker = speaker;
            this.rec = rec;
        }

        public int getBegin() {
            return begin;
        }

        public void setBegin(int begin) {
            this.begin = begin;
        }

        public int getEnd() {
            return end;
        }

        public void setEnd(int end) {
            this.end = end;
        }

        public String getSpeaker() {
            return speaker;
        }

        public void setSpeaker(String speaker) {
            this.speaker = speaker;
        }

        public String getRec() {
            return rec;
        }

        public void setRec(String rec) {
            this.rec = rec;
        }
    }
}
